package com.magicsoft.share.ui.main;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.magicsoft.share.R;
import com.magicsoft.share.bean.article.ArticleContent;
import com.magicsoft.share.constant.AppDavikActivityMgr;
import com.magicsoft.share.constant.SPKey;
import com.magicsoft.share.customview.alertview.AlertView;
import com.magicsoft.share.customview.alertview.OnItemClickListener;
import com.magicsoft.share.ui.article.AddArticleActivity;
import com.magicsoft.share.ui.article.AddNewArticleActivity;
import com.magicsoft.share.ui.exchange.ExchangeFragment;
import com.magicsoft.share.ui.exchange.ShopCartFragment;
import com.magicsoft.share.ui.my.MyFragment;
import com.magicsoft.share.ui.promote.PromoteFragment;
import com.magicsoft.share.ui.share.ShareFragment;
import com.magicsoft.share.utils.OssTool;
import com.magicsoft.share.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.rbtn_share)
    RadioButton rbtnShare;
    @BindView(R.id.rbtn_exchange)
    RadioButton rbtnExchange;
    @BindView(R.id.rbtn_promote)
    RadioButton rbtnPromote;
    @BindView(R.id.rbtn_my)
    RadioButton rbtnMy;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.fl_main)
    LinearLayout flMain;
    @BindView(R.id.imageView)
    ImageView imageView;
    private FragmentManager fragmentManager;
    private ArrayList<Fragment> fragmentList;

    public int currentIndex = 0;
    //当前显示的fragment
    private static final String CURRENT_FRAGMENT = "STATE_FRAGMENT_SHOW";
    private ShareFragment shareFragment;
    private ExchangeFragment exchangeFragment;
    private MyFragment myFragment;
    private PromoteFragment promoteFragment;
    private ShopCartFragment shopCartFragment;
    private Fragment currentFragment = new ShareFragment();
    private List<LocalMedia> selectList;
    private ArrayList<ArticleContent> articleContents;
    private OssTool ossManager;
    private ArrayList<String> filePath;
    private AlertView alertView;
    private boolean isExit;
    private ArrayList<String> urls;
    private int position = -1;
    private SweetAlertDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        initData(savedInstanceState);
        AppDavikActivityMgr.getScreenManager().addActivity(this);
        radioGroup.setOnCheckedChangeListener(this);

        ossManager = OssTool.getInstance().init(this);

        initDialog();
        initImgDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // ImmersionBar.with(this).destroy();
        AppDavikActivityMgr.getScreenManager().removeActivity(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.rbtn_share:
                currentIndex = 0;
                showFragment();
                break;
            case R.id.rbtn_exchange:
                currentIndex = 1;
                showFragment();
                break;
            case R.id.rbtn_promote:

                String string = SPUtils.getInstance().getString(SPKey.TOKEN);
                if (!string.equals("") && string != null) {
                    currentIndex = 2;
                    showFragment();
                } else {
                    alertView.show();
                }

                break;
            case R.id.rbtn_my:
                String string1 = SPUtils.getInstance().getString(SPKey.TOKEN);
                if (!string1.equals("") && string1 != null) {
                    currentIndex = 3;
                    showFragment();
                } else {
                    alertView.show();
                }

                break;
            default:
                break;
        }
    }

    private void initData(Bundle savedInstanceState) {
        fragmentManager = getSupportFragmentManager();
        fragmentList = new ArrayList<>();
        if (savedInstanceState != null) { // “内存重启”时调用

            //获取“内存重启”时保存的索引下标
            currentIndex = savedInstanceState.getInt(CURRENT_FRAGMENT, 0);

            fragmentList.removeAll(fragmentList);
            fragmentList.add(fragmentManager.findFragmentByTag(String.valueOf(0)));
            fragmentList.add(fragmentManager.findFragmentByTag(String.valueOf(1)));
            fragmentList.add(fragmentManager.findFragmentByTag(String.valueOf(2)));
            fragmentList.add(fragmentManager.findFragmentByTag(String.valueOf(3)));


            //恢复fragment页面
            restoreFragment();

        } else {//正常启动时调用
            shareFragment = new ShareFragment();
            exchangeFragment = new ExchangeFragment();
            promoteFragment = new PromoteFragment();
            shopCartFragment = new ShopCartFragment();
            myFragment = new MyFragment();
            fragmentList.add(shareFragment);
            fragmentList.add(exchangeFragment);
            fragmentList.add(shopCartFragment);
            fragmentList.add(myFragment);
            showFragment();
        }
    }

    /**
     * 展示Fragment 解决Fragment切换时丢失数据
     */
    public void showFragment() {

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (!fragmentList.get(currentIndex).isAdded()) {
            fragmentTransaction.hide(currentFragment)
                    .add(R.id.fl_main, fragmentList.get(currentIndex), String.valueOf(currentIndex));
        } else {
            fragmentTransaction.hide(currentFragment)
                    .show(fragmentList.get(currentIndex));
        }
        currentFragment = fragmentList.get(currentIndex);
        fragmentTransaction.commit();
    }


    /**
     * 当程序在后台长时间停留时，如果不做操作会出现Fragment重叠现象
     */
    private void restoreFragment() {

        FragmentTransaction mBeginTreansaction = fragmentManager.beginTransaction();

        for (int i = 0; i < fragmentList.size(); i++) {

            if (i == currentIndex) {
                mBeginTreansaction.show(fragmentList.get(i));
            } else {
                mBeginTreansaction.hide(fragmentList.get(i));
            }

        }

        mBeginTreansaction.commit();

        //把当前显示的fragment记录下来
        currentFragment = fragmentList.get(currentIndex);

    }

    @OnClick(R.id.imageView)
    public void onViewClicked() {

        String string = SPUtils.getInstance().getString(SPKey.TOKEN);
        if (!string.equals("") && string != null) {
            takePhoto();
        } else {
            alertView.show();

        }


    }

    private void initDialog() {
        alertView = new AlertView.Builder().setContext(this).setTitle("检测到您尚未登录，是否现在登录？").setStyle(AlertView.Style.Alert).setCancelText("否").setOthers(new String[]{"是"}).setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {

                if (position == -1) {
                    alertView.dismiss();

                } else {
                    alertView.dismiss();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);

                }
            }
        }).build();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    int position = 0;
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    articleContents = new ArrayList<>();
                    filePath = new ArrayList<>();
                    urls = new ArrayList<>();
                    for (int i = 0; i < selectList.size(); i++) {
                        articleContents.add(new ArticleContent());
                        Log.e("path",articleContents.toArray().toString());
                        filePath.add(selectList.get(i).getCompressPath());
                        Log.d("lyf", "onActivityResult: " + selectList.get(i).getCompressPath());
                    }


                    position=-1;
                    dialog.show();
                    uploadImg();
                    break;
                default:
                    break;
            }
        }
    }

    private void uploadImg() {

        position++;
        ossManager.upload("article", filePath.get(position), new OssTool.uploadListener() {
            @Override
            public void onSuccess(String url) {
                urls.add(url);
                Log.d("lyf", "onSuccess: " + urls);
                if (urls.size() == filePath.size()) {
                    position = -1;

                    for (int j = 0; j < articleContents.size(); j++) {
                        articleContents.get(j).setImg(urls.get(j));
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                            Log.d("lyf", "startActivity: ");
                            Intent intent = new Intent(MainActivity.this, AddArticleActivity.class);
//                            Intent intent = new Intent(MainActivity.this, AddNewArticleActivity.class);
                            intent.putExtra("articleContents", articleContents);
                            startActivity(intent);
                        }
                    });
                } else {

                    uploadImg();

                }
            }

            @Override
            public void onFail() {
                dialog.dismiss();
                position = -1;
            }
        });
    }

    private void initImgDialog() {
        dialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.PROGRESS_TYPE);
        dialog.getProgressHelper().setBarColor(R.color.main);
        dialog.setTitleText("加载图片中...");
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {

                ossManager.cancel();
            }
        });
    }

    private void takePhoto() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(MainActivity.this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                .theme(R.style.picture_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(20)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                // .previewVideo()// 是否可预览视频 true or false
                // .enablePreviewAudio() // 是否可播放音频 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                // .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                //    .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //     .enableCrop()// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                // .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                //  .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                //  .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                .isGif(true)// 是否显示gif图片 true or false
                //.compressSavePath("/CustomPath")//压缩图片保存地址
                //   .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                //   .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                //    .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                //   .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                //     .selectionMedia(false)// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                // .cropCompressQuality()// 裁剪压缩质量 默认90 int
                //   .minimumCompressSize(100)// 小于100kb的图片不压缩
                //    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                // .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                //   .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                //  .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                //   .videoQuality()// 视频录制质量 0 or 1 int
                // .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                //  .recordVideoSecond()//视频秒数录制 默认60s int
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


    private long firstTime = 0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    return true;
                } else {
                    AppDavikActivityMgr.getScreenManager().removeAllActivity();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

}
